from django.shortcuts import render, redirect, HttpResponse
from app02 import models
from app02.utils.pagination import Pagination
from django import forms
from app02.utils.form import UserModelForm
from app02.utils.bootstrap import BootStrapForm
from django.core.exceptions import ValidationError

from app02.utils.code import check_code
from io import BytesIO

from app02.utils.encrypt import md5


# Form 手写字段
class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput(),
        required=True
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(),
        required=True
    )
    code = forms.CharField(
        label="图片验证码",
        widget=forms.TextInput(),
        required=True
    )

    # 钩子方法
    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        print(md5(pwd))
        return md5(pwd)


"""
ModelForm  直接从数据库中拿(orm)字段
class LoginModelForm(forms.ModelForm):
    class Meta:
        model = models.adminis
        fields = ["username","password"]
"""


def login(request):
    """ 登入 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 获取到的用户名和密码
        # print(form.cleaned_data)  {'username': '1111', 'password': 'cec3defa99ea60f49ae42dc4e1884693','code':xxx}

        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', '')
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'login.html', {'form': form})

        # 去数据库校验用户名和密码是否正确，获取用户对象，没有返回None
        # admin_object = models.adminis.objects.filter(username=form.cleaned_data['username'],password=form.cleaned_data['password']).first()
        admin_object = models.adminis.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误!!")
            return render(request, 'login.html', {'form': form})

        # 用户名和密码正确
        # 网站生成随机字符串，写到用户浏览器的cookie中，再写入到服务器的session中
        request.session["info"] = {'id': admin_object.id, 'name': admin_object.username}
        # session可以保存7天
        request.session.set_expiry(60 * 60 * 24 / 7)

        return redirect("/admin/list/")

    return render(request, 'login.html', {'form': form})


def logout(request):
    """ 注销 """
    request.session.clear()

    return redirect('/login/')


def image_code(request):
    """ 生成图片验证码 """
    # 调用pillow函数，生成图片
    img, code_string = check_code()
    # 写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    # 给session设置60秒超时
    request.session.set_expiry(60)

    # 写入内存
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
